package com.onelap.bls.treadmillcalibration.activity.index;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.bls.blslib.eventbus.Event;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.onelap.bls.treadmillcalibration.R;
import com.onelap.bls.treadmillcalibration.activity.entry.EntryActivity;
import com.onelap.bls.treadmillcalibration.config.Constant;
import com.onelap.bls.treadmillcalibration.service.UartService;
import com.onelap.bls.treadmillcalibration.utils.BLeUtil;
import com.onelap.bls.treadmillcalibration.utils.CommonUtil;
import com.onelap.bls.treadmillcalibration.utils.PermissionHelper;
import com.onelap.bls.treadmillcalibration.utils.PermissionUtil;
import com.onelap.bls.treadmillcalibration.utils.ScanRecordUtil;
import com.onelap.bls.treadmillcalibration.utils.TitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_DATA_AVAILABLE;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_GATT_CONNECTED;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_GATT_DISCONNECTED;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_GATT_SERVICES_DISCOVERED;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.DEVICE_DOES_NOT_SUPPORT_UART;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.EXTRA_BATTERY_LEVEL;

public class IndexActivity extends BaseActivity implements BLeUtil.BleUtilCallback {

    @BindView(R.id.rv_device_list)
    RecyclerView rvDeviceList;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.btn_connect)
    Button btnConnect;

    private List<DeviceBean> bluetoothDeviceList = new ArrayList<>();
    private DeviceListAdapter deviceListAdapter;
    private BluetoothAdapter bluetoothAdapter;
    private BLeUtil bLeUtil;

    private boolean searchDeviceState = false;  //搜索设备的状态，默认未搜索
    private int defaultSelectDevice = -1; //默认选中的设备
    private DeviceBean selectDeviceBean = null;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    public void onStickyEventBusCome(Event event) {
        super.onStickyEventBusCome(event);
        if (event.getCode() == 0) {
            bluetoothDeviceList.clear();
            deviceListAdapter.notifyDataSetChanged();
            bLeUtil.searchBLeDevice(bluetoothAdapter, true);
        }
    }

    @Override
    protected void initParams() {
        super.initParams();

        bLeUtil = new BLeUtil(this);

        deviceListAdapter = new DeviceListAdapter(bluetoothDeviceList);

        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager == null) {
            ToastUtils.showLong("Bluetooth is not available ");
            CommonUtil.delayClose(2000);
        }

        assert bluetoothManager != null;
        bluetoothAdapter = bluetoothManager.getAdapter();

        if (bluetoothAdapter == null) {
            ToastUtils.showLong("Bluetooth is not available ");
            CommonUtil.delayClose(2000);
        }

        if (!PermissionUtils.isGranted(Constant.PERMISSION_LIST)) {
            LogUtils.i("111111111111111111111");
            PermissionUtil.applyForPermission(Constant.PERMISSION_LIST);
        }
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_index;
    }

    @Override
    protected void initFvb() {
        super.initFvb();
        ButterKnife.bind(this);

    }

    @Override
    protected void initTitle() {
        super.initTitle();
        TitleBar titleBar = findViewById(R.id.tb_title_bar);
        titleBar.setTitle("设备选择");
        titleBar.setBackgroundColor(Color.BLACK);
        titleBar.setTitleColor(Color.WHITE);
    }

    @Override
    protected void initView() {
        super.initView();
        rvDeviceList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvDeviceList.setAdapter(deviceListAdapter);
        deviceListAdapter.bindToRecyclerView(rvDeviceList);
        deviceListAdapter.setEmptyView(R.layout.view_empty_list);
    }

    @Override
    protected void initListener() {
        super.initListener();
        deviceListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LogUtils.i("bluetoothDeviceList.get(position).getDevice().getAddress()", bluetoothDeviceList.get(position).getDevice().getAddress());
                if (defaultSelectDevice != -1)
                    bluetoothDeviceList.get(defaultSelectDevice).setSelect(false);
                bluetoothDeviceList.get(position).setSelect(true);
                defaultSelectDevice = position;
                selectDeviceBean = bluetoothDeviceList.get(position);
                deviceListAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initResume() {
        super.initResume();
    }

    @OnClick(R.id.btn_search)
    public void onBtnSearchClicked() {
        //如果没有响应权限，则申请权限
        if (bluetoothAdapter.isEnabled()) {
            bLeUtil.searchBLeDevice(bluetoothAdapter, !searchDeviceState);
        } else {
            bLeUtil.openBluetooth();
        }
    }

    @OnClick(R.id.btn_connect)
    public void onBtnConnectClicked() {

        bLeUtil.searchBLeDevice(bluetoothAdapter, false);

        if (bluetoothDeviceList.size() == 0) {
            ToastUtils.showLong("请搜索可用设备");
            return;
        }

        if (selectDeviceBean == null) {
            ToastUtils.showLong("请选择可用设备");
            return;
        }

        if (ScanRecordUtil.getBroadcastPacketStatue(selectDeviceBean.getBroadcastPacket()) == ScanRecordUtil.BroadcastPacketStatue.NonConnectableUndirectedEventType) {
            ToastUtils.showLong("当前设备不可连接");
            return;
        }

        bLeUtil.bindBleService(getActivity(), UartService.class,
                ACTION_GATT_CONNECTED,
                ACTION_GATT_DISCONNECTED,
                ACTION_GATT_SERVICES_DISCOVERED,
                ACTION_DATA_AVAILABLE,
                EXTRA_BATTERY_LEVEL,
                DEVICE_DOES_NOT_SUPPORT_UART);
        /*if (!ServiceUtils.isServiceRunning(UartService.class)) {
            bLeUtil.bindBleService(getActivity(), UartService.class,
                    ACTION_GATT_CONNECTED,
                    ACTION_GATT_DISCONNECTED,
                    ACTION_GATT_SERVICES_DISCOVERED,
                    ACTION_DATA_AVAILABLE,
                    EXTRA_BATTERY_LEVEL,
                    DEVICE_DOES_NOT_SUPPORT_UART);
        } else {
            if (bluetoothLeService.connect(selectBluetoothDevice.getAddress())) {
                Intent intent2 = new Intent();
                intent2.putExtra("Device", new Gson().toJson(selectBluetoothDevice));
                intent2.setClass(getActivity(), EntryActivity.class);
                getActivity().startActivity(intent2);
            } else {
                ToastUtils.showLong("当前设备不可连接");
            }
        }*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.REQUEST_INTENT_ENABLE_BLUETOOTH:
                LogUtils.i(resultCode);
                if (resultCode == Activity.RESULT_OK) {
                    bLeUtil.searchBLeDevice(bluetoothAdapter, true);
                } else if (resultCode == Activity.RESULT_CANCELED)
                    bLeUtil.openBluetooth();
                break;
        }
    }


    @Override
    public void onBleUtilCallback(int status, BluetoothDevice device, int rssi, byte[] scanRecord, IBinder rawBinder, Intent intent) {
        switch (status) {
            case BLeUtil.STATUS_DEVICE_FIND:
                if (!judgeDeviceAlreadyExist(device)) {
                    deviceListAdapter.addData(new DeviceBean(false, device, rssi, scanRecord));
                }
                break;
            case BLeUtil.STATUS_SEARCH_START:
                btnSearch.setText("Searching......");
                searchDeviceState = true;
                break;
            case BLeUtil.STATUS_SEARCH_STOP:
                btnSearch.setText("Search");
                searchDeviceState = false;
                break;
            case BLeUtil.STATUS_SERVICE_CONNECTED:
                //private BluetoothDevice selectBluetoothDevice = null;//选中的设备
                UartService bluetoothLeService = ((UartService.LocalBinder) rawBinder).getService();
                LogUtils.i("onServiceConnected mService=", bluetoothLeService);
                if (!bluetoothLeService.initialize()) {
                    LogUtils.i("onServiceConnected mService=", "Unable to initialize Bluetooth");
                    AppUtils.exitApp();
                }
                /*if (bluetoothLeService.connect(selectDeviceBean.getDevice().getAddress())) {*/
                Intent intent2 = new Intent();
                intent2.putExtra("DeviceBean", new Gson().toJson(selectDeviceBean));
                intent2.setClass(getActivity(), EntryActivity.class);
                getActivity().startActivity(intent2);
                /*} else {
                    ToastUtils.showLong("当前设备不可连接");
                }*/
                break;
        }
    }

    /**
     * 判断列表中是否已经存在设备信息
     */
    private boolean judgeDeviceAlreadyExist(BluetoothDevice device) {
        for (DeviceBean deviceBean : bluetoothDeviceList) {
            if (device.getAddress().equals(deviceBean.getDevice().getAddress()))
                return true;
        }
        return false;
    }


    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setMessage("Exit the application ? ")
                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("CONFIRM", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AppUtils.exitApp();
                    }
                })
                .create().show();
    }
}
